<?php
namespace Mobile\Service;
use Mobile\Controller\WechatController;
class UserService extends BaseService
{

    public $memberModel;
    public $memberappModel;
    public function __construct () {
        $this->memberModel = new \Mobile\Model\memberModel();
        $this->memberappModel = M('member_app');
    }

    public function handleAppUser ($info) {
        $appUser = array(
            'openid' => $info['openid'],
            'nickname' => $info['nickname'],
            'headimgurl' => $info['headimgurl'],
            'unionid' => $info['unionid'],
            'create_time' => date('Y-m-d H:i:s')
        );
            
        $res1 = $this->memberappModel->where(array('openid'=>$appUser['openid']))->find();
        if(!$res1) {
            $this->memberappModel->add($appUser);
        }else{
            unset($appUser['create_time']);
            $this->memberappModel->where(array('openid'=>$appUser['openid']))->save($appUser);
        }
        $res2 = $this->memberModel->where(array('unionid'=>$appUser['unionid']))->find();
        if(!$res2) {
            return_json(1,'请先关注公众号“全球伯乐”');
            //新用户
            $newUser = array(
                'unionid' => $appUser['unionid'],
                'nickname' => $appUser['nickname'],
                'headimgurl' => $appUser['headimgurl'],
                'create_time' => date('Y-m-d H:i:s'),
                'sex' => $info['sex'],
                'province' => $info['province'],
                'city' => $info['city'],
                'country' => $info['country'],
                'regfrom' => 'app'
            );
            $uid = $this->memberModel->add($newUser);
        }else{
            $uid = $res2['uid'];
        }
        return $uid;
    }

    public function handleWechatUser ($info) {
        $wechatUser = array(
            'unionid' => $appUser['unionid'],
            'nickname' => $appUser['nickname'],
            'headimgurl' => $appUser['headimgurl'],
            'create_time' => date('Y-m-d H:i:s'),
            'sex' => $info['sex'],
            'province' => $info['province'],
            'city' => $info['city'],
            'country' => $info['country'],
            'regfrom' => 'app'
        );
    }

    public function getUidByCode ($code) {
        C('WECHAT_APPID',C('OPEN_APPID'));
        C('WECHAT_APPKEY',C('OPEN_APPKEY'));
        $options = array(
            'WECHAT_APPID' => C('OPEN_APPID'),
            'WECHAT_APPKEY' => C('OPEN_APPKEY')
        );
        $wechat=new WechatController($options);
        $_GET['code'] = $code;
        $tokenArr = $wechat->getOauthAccessToken();
        $userinfo = $wechat->getOauthUserinfo($tokenArr['access_token'],$tokenArr['openid']);
        file_put_contents('uni.txt',json_encode($userinfo).PHP_EOL, FILE_APPEND);

        if($userinfo['unionid']&&$userinfo['openid']) {
            return $this->handleAppUser($userinfo);
        }
        return false;
    }
}
